import { defineStore } from "pinia";
import { AuthState } from "@/interface/store";
import { getFlatMenuList, getShowMenuList } from "@/utils/menu";
import { dayjs } from "element-plus";
import piniaPersistConfig from "@/stores/piniaPersist";
import { getUserInfo, getAuthMenuListApi } from "@/api/app";

export const useAuthStore = defineStore({
  id: "authStore",
  state: (): AuthState => ({
    authMenuList: [],
    token: "", //用配置文件的userInfo
    userInfo: null, //用户对象信息
    fiscalYear: dayjs(new Date()).format("YYYY"), //业务年度
  }),
  getters: {
    authMenuListGet: (state) => state.authMenuList,
    //扁平化菜单，主要用于添加路由
    flatMenuListGet: (state) => getFlatMenuList(state.authMenuList),
    //左侧菜单栏渲染
    showMenuListGet: (state) => getShowMenuList(state.authMenuList),
  },
  actions: {
    async getAuthMenuList() {
      const { data } = await getAuthMenuListApi();
      this.authMenuList = data;
    },
    async getUserInfo() {
      const res = await getUserInfo();
      const data = res.data as any;
      if (data) {
        this.userInfo = data;
      }
      return data;
    },
    setToken(token: string) {
      this.token = token;
    },
    setUserInfo(userInfo: any) {
      this.userInfo = userInfo;
    },
    setFiscalYear(val: number | string) {
      this.fiscalYear = val;
    },
    disabledDate(time) {
      const startTime = new Date(Number(this.fiscalYear), 0, 1);
      const endTime = new Date(Number(this.fiscalYear), 11, 31);
      if (Number(this.fiscalYear) < new Date().getFullYear()) {
        return time.getTime() > endTime || time.getTime() < startTime;
      }
      return time.getTime() > Date.now() || time.getTime() < startTime;
    },
  },
  persist: piniaPersistConfig("auth", localStorage, ["fiscalYear", "userInfo", "token"]),
});
